package source.module.carousel;

import source.kernel.Container;
import source.kernel.serialization.json.Json;
import source.table.history;

import java.io.IOException;
import java.math.BigInteger;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Hai Thomson
 */
public class Carousel_applicationdata {
	public static void run() throws IOException, SQLException {
		String applicationid = Container.app().request.getParameter("applicationid");
		String dateline = Integer.toString((int) (System.currentTimeMillis() / 1000) - Integer.valueOf(Container.app().request.getParameter("dateline")));
		String now      = Integer.toString((int) (System.currentTimeMillis() / 1000));

		Map result = new HashMap();

		List<Map> items = ((source.table.items) Container.table("items")).fetchItem(applicationid);
		if (items != null) {
			for (Map item : items) {
				if ((int)item.get("value_type") == 3) {
					String itemid = ((BigInteger)item.get("itemid")).toString();
					List data = ((source.table.history_uint) Container.table("history_uint")).fetchdata(itemid, dateline, now);
					if (data != null && data.size() > 0) {
						result.put(conversionItemName((String) item.get("name"), (String) item.get("key_")), data);
					}
					continue;
				}

				String itemid = ((BigInteger)item.get("itemid")).toString();
				List data = ((source.table.history) Container.table("history")).fetchdata(itemid, dateline, now);
				if (data != null && data.size() > 0) {
					result.put(conversionItemName((String) item.get("name"), (String) item.get("key_")), data);
				}
			}
		}

		Container.app().response.getWriter().print(Json.toJson(result));
		Container.app().response.getWriter().flush();
	}

	public static String conversionItemName(String name, String key_) {
		if (name == null || key_ == null || name.equals("") || key_.equals("")) {
			// System.out.println("1 " + name);
			return name;
		}

		String regEx = "\\[([\\s\\S]*)\\]";
		Pattern pattern = Pattern.compile(regEx);
		Matcher matcher = pattern.matcher(key_);
		String[] sp = null;
		if (matcher.find()) {
			sp = matcher.group(0).substring(1, matcher.group(0).length() - 1).split(",");
		} else {
			// System.out.println("2 " + name + " " + key_);
			return name;
		}

		regEx = "\\$\\d";
		pattern = Pattern.compile(regEx);
		matcher = pattern.matcher(name);

		String tregEx = "\\d";
		Pattern tpattern = Pattern.compile(tregEx);
		while (matcher.find()) {
			String tmp = matcher.group(0);
			Matcher tmatcher = tpattern.matcher(tmp);
			if (tmatcher.find()) {
				int s = Integer.valueOf(tmatcher.group());
				name = name.replaceAll("\\" + tmp, sp[s-1]);
			}
		}

		return name;
	}
}
